package com.imooc.miaosha.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 模块描述: <br>
 * ()
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/17 10:30
 * @since: 1.8.0
 * @version: 1.0.0
 */
public class CookieUtils {

    /**
     * 设置cookie的基础方法
     *
     * @param name
     * @param obj
     * @param expireSeconds
     */
    public static void setCookie(String name, Object obj, Integer expireSeconds) {
        Cookie cookie = new Cookie(name, obj.toString());
        cookie.setPath("/");
        cookie.setMaxAge(expireSeconds);
        HttpServletResponse response = ServletUtils.getResponse();
        response.addCookie(cookie);
    }

    /**
     * 根据name获取cookie值
     *
     * @param name
     * @return
     */
    public static String getCookie(String name) {
        HttpServletRequest request = ServletUtils.getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(name)) {
                return cookies[i].getValue();
            }
        }
        return null;
    }

}
